//
cc.Class({
    extends: cc.Component,

    properties: {
        target: {
            default: null,
            type: cc.Node
        },
        joystick: {
            default: null,
            type: cc.Node
        },
    },
    onLoad:function () {

    },
    start:function () {

    },
    update:function (dt) {
        var keyboardSimulator = this.target.getComponent("KeyboardSimulator");
        var speed = 2;
        var degrees = undefined;
        var velocity = undefined;
        if (keyboardSimulator && !cc.sys.isNative) {
            var moveDirection = 0;
            var rotationDelta = 0;
            var velocityScale = cc.v2(1, 1);
            var targetRotation = this.target.angle;
            if (keyboardSimulator.allKeys[38] || keyboardSimulator.allKeys[87]) {
                moveDirection = 1;
            }
            else if (keyboardSimulator.allKeys[40] || keyboardSimulator.allKeys[83]) {
                moveDirection = -1;
            }
            if (keyboardSimulator.allKeys[37] || keyboardSimulator.allKeys[65]) {
                rotationDelta = -2;
            }
            else if (keyboardSimulator.allKeys[39] || keyboardSimulator.allKeys[68]) {
                rotationDelta = 2;
            }
            if (rotationDelta != 0) {
                this.target.angle = (targetRotation - rotationDelta);
            }
            if (moveDirection != 0) {
                var desiredPosition = cc.v2(0, 0);
                var verlocityUnit = cc.v2(Math.cos(cc.misc.degreesToRadians(this.target.angle)), Math.sin(cc.misc.degreesToRadians(this.target.angle)));
                var velocity = verlocityUnit.mul(speed);
                velocity.x *= Math.abs(velocityScale.x);
                velocity.y *= Math.abs(velocityScale.y);
                if (moveDirection == 1) {
                    desiredPosition = velocity;
                }   
                else if (moveDirection == -1) {
                    desiredPosition = velocity.mul(-1);
                }
                this.target.setPosition(desiredPosition.add(this.target.getPosition()));
            }
        }
        else {
            degrees = this.joystick.getComponent("SneakyJoystickCore").getDegrees();
            velocity = this.joystick.getComponent("SneakyJoystickCore").getVelocity();
            this.target.angle = degrees;
            var verlocityUnit = cc.v2(Math.cos(cc.misc.degreesToRadians(degrees)), Math.sin(cc.misc.degreesToRadians(degrees)));
            var fullVelocity = verlocityUnit.mul(speed);
            fullVelocity.x *= Math.abs(velocity.x);
            fullVelocity.y *= Math.abs(velocity.y);
            this.target.setPosition(this.target.getPosition().add(fullVelocity));
        }  
    },
});
